<?php

namespace App\Http\Controllers;

use App\Models\AdminUser;
use App\Models\CaseDescribe;
use App\Models\Course;
use App\Models\Doctor;
use App\Models\DoctorWorks;
use App\Models\FinancialStatementsLog;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\PayRefundLog;
use App\Models\ProductGoods;
use App\Models\Store;
use App\Models\StoreOrder;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Mrgoon\AliSms\AliSms;
use Illuminate\Support\Facades\DB;
//============支付宝支付===========
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;

/***
 * Class PaymentController
 * @package App\Http\Controllers
 * 支付宝支付
 */
class PaymentController extends BaseController
{
    private static function pay($data){
        //1. 设置参数（全局只需设置一次）
        Factory::setOptions(self::getOptions());
        try {
            //2. 发起API调用（以支付能力下的统一收单交易创建接口为例）
//            $result = Factory::payment()->common()->create($data['subject'], $data['sn'], $data['pay_price'], $data['user_id'],$data['order_type']);
            $result = Factory::payment()->app()->pay($data['subject'], $data['sn'], $data['pay_price']);
            $responseChecker = new ResponseChecker();
            //3. 处理响应或异常
            if ($responseChecker->success($result)) {
                return  $result->body;
                echo "调用成功". PHP_EOL;
            } else {
                echo "调用失败，原因：". $result->msg."，".$result->subMsg.PHP_EOL;
            }
        } catch (Exception $e) {
            echo "调用失败，". $e->getMessage(). PHP_EOL;;
        }
    }



    private function baseReturn($data)
    {
        Factory::setOptions(self::getOptions());
        try {
            //2. 发起API调用（以支付能力下的统一收单交易创建接口为例）
            //这里使用三段 表示 具体看手册 https://opendocs.alipay.com/open/54/103419/
            $result = Factory::payment()->common()
                ->optional("out_request_no",$data['back_sn']) //out_request_no 是退款的商户自定义编号 不能重复 重复的话会导致后一次的失败
                ->refund($data['sn'], $data['money']); // refund的是退款的方法 还有其他方法可以参见手册  第一个参数为支付时的商户自定义订单号 第二个参数为需要退款的金额
            //这里查看 手册 https://github.com/alipay/alipay-easysdk/blob/master/APIDoc.md
            $responseChecker = new ResponseChecker();
            //3. 处理响应或异常
            if ($w = $responseChecker->success($result)) {
                $str = substr($data['sn'],0,2);
                if($str == 'st'){
                    $order = (new StoreOrder())->where([['sn','=',$data['sn']]])->first();
                    $order->order_type = 6;
                }else{
                    $order = (new Order())->where([['sn','=',$data['sn']]])->first();
                }
                $backs["trade_no"] = $result->tradeNo;
                $backs["out_trade_no"] = $result->outTradeNo;
                $backs["total_amount"] = $data['money'];
                PayRefundLog::addAliPayRefundLog($backs,$order,2,1);
                echo 'success';
                return "success";
//                return 'success';
//                return $w;
                //dump($w);
                //处理其他内容
                return $result->body;
                echo "调用成功" . PHP_EOL;
            } else {
                echo "调用失败，原因：" . $result->msg . "，" . $result->subMsg . PHP_EOL;
                return $result->subMsg;
            }
        } catch (Exception $e) {
            echo "调用失败，" . $e->getMessage() . PHP_EOL;;
        }
        // $this->ok(200, '成功', ['data' => $res]);
    }



    /***
     * @throws \Exception
     * 退款
     */
    private function baseReturn_old($data)
    {
        Factory::setOptions(self::getOptions());
        try {
            //2. 发起API调用（以支付能力下的统一收单交易创建接口为例）
            //这里使用三段 表示 具体看手册 https://opendocs.alipay.com/open/54/103419/
            $result = Factory::payment()->common()
                ->optional("out_request_no",$data['back_sn']) //out_request_no 是退款的商户自定义编号 不能重复 重复的话会导致后一次的失败
                ->refund($data['sn'], $data['money']); // refund的是退款的方法 还有其他方法可以参见手册  第一个参数为支付时的商户自定义订单号 第二个参数为需要退款的金额
            //这里查看 手册 https://github.com/alipay/alipay-easysdk/blob/master/APIDoc.md
            $this->writeLog($result);
            $responseChecker = new ResponseChecker();
            //3. 处理响应或异常
            if ($w = $responseChecker->success($result)) {
                return $w;
                //dump($w);
                //处理其他内容

                // return $result->body;
                echo "调用成功" . PHP_EOL;
            } else {
                echo "调用失败，原因：" . $result->msg . "，" . $result->subMsg . PHP_EOL;
            }
        } catch (Exception $e) {
            echo "调用失败，" . $e->getMessage() . PHP_EOL;;
        }
        // $this->ok(200, '成功', ['data' => $res]);
    }




    private static function getOptions()
    {
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = config('omnipay.options.app_id');//'<-- 请填写您的AppId，例如：2019022663440152 -->';
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        $options->merchantPrivateKey = config('omnipay.options.private_key');//'<-- 请填写您的应用私钥，例如：MIIEvQIBADANB ... ... -->';
        $options->alipayCertPath = config('omnipay.options.alipayCertPath');// '<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->';
        $options->alipayRootCertPath = config('omnipay.options.alipayRootCertPath');// '<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt" -->';
        $options->merchantCertPath = config('omnipay.options.merchantCertPath');// '<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->';
        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
//        $options->alipayPublicKey = config('omnipay.options.public_key');//'<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->';
        //可设置异步通知接收服务地址（可选）
        $options->notifyUrl = config('omnipay.options.notify_url');//"<-- 请填写您的支付类接口异步通知接收服务地址，例如：https://www.test.com/callback -->";
        return $options;
    }


//    private static function getOptions()
//    {
//        $options = new Config();
//        $options->protocol = 'https';
//        $options->gatewayHost = 'openapi.alipay.com';
//        $options->signType = 'RSA2';
//        $options->appId = config('omnipay.options.app_id');//'<-- 请填写您的AppId，例如：2019022663440152 -->';
//        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
//        $options->merchantPrivateKey = config('omnipay.options.private_key');//'<-- 请填写您的应用私钥，例如：MIIEvQIBADANB ... ... -->';
//        $options->alipayCertPath = config('omnipay.options.alipayCertPath');// '<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->';
//        $options->alipayRootCertPath = config('omnipay.options.alipayRootCertPath');// '<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt" -->';
//        $options->merchantCertPath = config('omnipay.options.merchantCertPath');
//        //$options->merchantPrivateKey = config('omnipay.options.private_key');//'<-- 请填写您的应用私钥，例如：MIIEvQIBADANB ... ... -->';
////        $options->alipayCertPath = '<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->';
////        $options->alipayRootCertPath = '<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt" -->';
////        $options->merchantCertPath = '<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->';
//        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
//        //$options->alipayPublicKey = config('omnipay.options.public_key');//'<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->';
//        //可设置异步通知接收服务地址（可选）
//        $options->notifyUrl = config('omnipay.options.notify_url');//"<-- 请填写您的支付类接口异步通知接收服务地址，例如：https://www.test.com/callback -->";
//        return $options;
//    }



    /**
     * @param Request $request
     * @return mixed
     * 2024-04-24 19:02:12: {"gmt_create":"2024-04-24 19:02:10","charset":"UTF-8","seller_email":"qq17768921671@163.com","subject":"100_\u5feb\u9012\u8d39\u5546\u5708\u652f\u4ed8","sign":"PvHZVamMjFNtjGK\/a+5FCDQU7UNdd2tLzOM1UogasCk2TxjMlBApXXbvm3qtQyS2sRcAyE1HCwb\/WI53tgN6V0I4nhGcr6JdvoU9o3Bz9zsGByFcYlo9KuLun42rnWH0qhBKVdymKBScfXYGXuaQtqJ651VAgWZJdPcSJ\/Ina9ghOU3\/E32HWWZNrdeiHk8iHjxWjI5sPTbJcN9yW7SU9d\/N7AJmcxNqOpTzt76mPuQbUysYCOameWXQrKroHOEA08hRDzlVnFtrNcgidwFz8rQtqCQtaS6ouwtqm3RjeFKaqNKFHqQ6b2m8pWJn6Ej6dk6Zs1i7dykZJ+3edgUZAw==","buyer_open_id":"061qYMZZ6WYyRSZgQQYLgo2ZwAKrO-pmidzd3nVqSXHBmUa","invoice_amount":"0.01","notify_id":"2024042401222190211040611486448463","fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"PCREDIT\"}]","notify_type":"trade_status_sync","trade_status":"TRADE_SUCCESS","receipt_amount":"0.01","app_id":"2021004144625161","buyer_pay_amount":"0.01","sign_type":"RSA2","seller_id":"2088340436366456","gmt_payment":"2024-04-24 19:02:10","notify_time":"2024-04-24 19:02:11","merchant_app_id":"2021004144625161","version":"1.0","out_trade_no":"2024042355554910","total_amount":"0.01","trade_no":"2024042422001440611422226883","auth_app_id":"2021004144625161","buyer_logon_id":"135****7629","point_amount":"0.00"}
    2024-04-24 19:02:12: {"gmt_create":"2024-04-24 19:02:10",
     * "charset":"UTF-8",
     * "seller_email":"qq17768921671@163.com",
     * "subject":"100_\u5feb\u9012\u8d39\u5546\u5708\u652f\u4ed8",
     * "sign":"PvHZVamMjFNtjGK\/a+5FCDQU7UNdd2tLzOM1UogasCk2TxjMlBApXXbvm3qtQyS2sRcAyE1HCwb\/WI53tgN6V0I4nhGcr6JdvoU9o3Bz9zsGByFcYlo9KuLun42rnWH0qhBKVdymKBScfXYGXuaQtqJ651VAgWZJdPcSJ\/Ina9ghOU3\/E32HWWZNrdeiHk8iHjxWjI5sPTbJcN9yW7SU9d\/N7AJmcxNqOpTzt76mPuQbUysYCOameWXQrKroHOEA08hRDzlVnFtrNcgidwFz8rQtqCQtaS6ouwtqm3RjeFKaqNKFHqQ6b2m8pWJn6Ej6dk6Zs1i7dykZJ+3edgUZAw==",
     * "buyer_open_id":"061qYMZZ6WYyRSZgQQYLgo2ZwAKrO-pmidzd3nVqSXHBmUa",
     * "invoice_amount":"0.01",
     * "notify_id":"2024042401222190211040611486448463",
     * "fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"PCREDIT\"}]",
     * "notify_type":"trade_status_sync",
     * "trade_status":"TRADE_SUCCESS",
     * "receipt_amount":"0.01",
     * "app_id":"2021004144625161",
     * "buyer_pay_amount":"0.01",
     * "sign_type":"RSA2",
     * "seller_id":"2088340436366456",
     * "gmt_payment":"2024-04-24 19:02:10",
     * "notify_time":"2024-04-24 19:02:11",
     * "merchant_app_id":"2021004144625161",
     * "version":"1.0",
     * "out_trade_no":"2024042355554910",
     * "total_amount":"0.01",
     * "trade_no":"2024042422001440611422226883",
     * "auth_app_id":"2021004144625161",
     * "buyer_logon_id":"135****7629",
     * "point_amount":"0.00"}
     *
     *
     */

    public function notify(Request $request)
    {
        $post = $request->input();
        $this->writeLog($post);
//        $this->writeLog($_POST);
//        Log::channel('daily')->info($post);
//        Log::channel('daily')->info($_POST);
//        $gateway = Omnipay::create(config('omnipay.gateway'));
//        $gateway->initialize(config('omnipay.options'));
//        $response = $gateway->completePurchase()->setParams($_POST)->send();
//        Log::channel('daily')->info($response);
//        Log::channel('daily')->info($response->isPaid());
        Factory::setOptions(self::getOptions());
//        $res = Factory::payment()->common()->verifyNotify($post);
        $res = Factory::payment()->common()->verifyNotify($post);
        $this->writeLog($res);
//        $this->writeLog($resq);
        if ($post['trade_status'] = "TRADE_SUCCESS") {
            $arr = explode('_', trim($post['subject']));
            if (isset($arr[0]) && ($arr[0] == '100')) { //商圈支付回调
                $store_order = new StoreOrder();
                $info_store_order = $store_order->where([['sn', '=', $post['out_trade_no']]])->first();
                if ($info_store_order->pay_status == 1) {
                    echo 'success';
                    die("success");
                }
                $lit['order_status'] = 1;
                $lit['pay_status'] = 1;
                $lit['pay_time'] = date("Y-m-d H:i:s", time());
                $store_order->where([['sn', '=', $post['out_trade_no']]])->update($lit);
                (new Store())->where([['id','=',$info_store_order->store_id]])->update(['topping' => $info_store_order->type, 'buy_type' => $info_store_order->type_id, "is_online" => 1]);
                echo 'success';
                die("success");
            } else {
                // 处理支付成功的情况
                // 根据返回的订单号查询订单数据
                $order = (new Order())->where([['sn', '=', $post['out_trade_no']]])->first();
                $order_goods = (new OrderGoods())->where([['order_id', '=', $order->id]])->first();
                if (empty($order)) {
                    echo 'fail';
                    die("fail");
                }
                if ($order->pay_status == 1) {
                    echo 'success';
                    die("success");
                }
                try {
                    DB::beginTransaction(); // 开始事务
                    $list['pay_time'] = date("Y-m-d H:i:s:", time());
                    $list['pay_status'] = 1;
                    if ($order->order_type == 1) {  //课程
                        $course = (new Course())->where([['id', '=', $order_goods->goods_id]])->first();
                        //判断课程是否是自己的工作室
                        if ($course->doc_studio_id == $order->work_id) {   //工作室自己的课程
                            //工作室加钱
                            (new DoctorWorks())->where([["id", '=', $order->work_id]])->increment("surplus", $order->self_work_price);
                        } else {
                            //工作室加钱
                            (new DoctorWorks())->where([["id", '=', $order->work_id]])->increment("surplus", $order->self_work_price);
                            (new DoctorWorks())->where([["id", '=', $course->doc_studio_id]])->increment("surplus", $order->share_work_price);
                        }
                        $list['delivery_time'] = date("Y-m-d H:i:s:", time());
                        $list['delivery_status'] = 1;
                        $list['receive_time'] = date("Y-m-d H:i:s:", time());
                        $list['receive_status'] = 1;
                        $list['order_status'] = 1;
                        //增加销量
                        (new Course())->where([['id', '=', $order_goods->goods_id]])->increment("buy_num", $order->goods_num);
                        //添加账单记录
                        $this->addStatements($order, $order_goods);

                    } else if ($order->order_type == 2) {  //商品
                        //增加销量
                        (new ProductGoods())->where([['id', '=', $order_goods->goods_id]])->increment("product_sales", $order->goods_num);
                        //减少库存
                        (new ProductGoods())->where([['id', '=', $order_goods->goods_id]])->decrement("product_stock", $order->goods_num);
                        //添加账单记录
                        $this->addStatements($order, $order_goods);
                    } else if ($order->order_type == 3 || $order->order_type == 4) {  //图文和电话
                        //增加销量
                        (new Doctor())->where([['id', '=', $order_goods->goods_id]])->increment("consult_num", 1);
                        //添加账单记录
                        $this->addStatements($order, $order_goods);
                    }
                    (new Order())->where([['id', '=', $order->id]])->update($list);
                    DB::commit(); // 提交事务
                    echo 'success';
                    die("success");
                } catch (Exception $e) {
                    echo 'fail';
                    DB::rollback(); // 回滚事务
                    die("fail");
                }

            }
        } else {
            echo 'fail';
        }
    }


    /**
     * 写入删除log
     */
    public function writeLog($data) {
        $filepath = base_path() . "/storage/logs/alipay/";
        if (!is_dir($filepath)) {
            mkdir($filepath);
        }
        $filename = "del_log" . date("Ymd") . ".txt";
        $file = $filepath . $filename;
        if (is_file($file)) {
            chmod($file, 0777);
            $fh = fopen($file, "a+");
        } else {
            $fh = fopen($file, "a+");
            chmod($file, 0777);
        }
        $content = json_encode($data);
        if ($fh) {
            fwrite($fh, date("Y-m-d H:i:s") . ": $content \r\n");
        }
        fclose($fh);
    }









    public function return(Request $request)
    {

    }

    /**
     * @param $order
     * @param $order_goods
     * @return bool
     * 添加账单
     * 价格待处理
     */
    public function addStatements($order, $order_goods)
    {
        $data['sn'] = $order->sn;
        $data['date_str'] = date("Y-m-d H:i:s", time());
        $data['goods_num'] = $order->goods_num;
        $data['names'] = $order_goods->goods_name;
        $data['work_id'] = $order->work_id;
        $data['goods_id'] = $order_goods->goods_id;
        $data['order_id'] = $order->id;
        $data['updated_at'] = date("Y-m-d H:i:s", time());
        $data['created_at'] = date("Y-m-d H:i:s", time());
        if ($order->order_type == 1) {  //课程
            $data['type'] = 1;
            $data['settle_status'] = 1;
            $data['add_or_sub'] = 1;
            $data['divide_type'] = 1;
            $course = (new Course())->where([['id', '=', $order_goods->goods_id]])->first();
            //判断课程是否是自己的工作室
            if ($course->doc_studio_id == $order->work_id) {   //工作室自己的课程
                $info = (new FinancialStatementsLog())
                    ->where([['order_id', '=', $order->order_id], ['work_id', '=', $order->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                    ->first();
                if (empty($info)) {
                    $data['money'] = $order->self_work_price;
                    $data['remarks'] = "课程收费";
                    return (new FinancialStatementsLog())->insert($data);
                }
                //工作室余额加钱
                (new DoctorWorks())
                    ->where([["id", '=', $order->work_id]])
                    ->increment("surplus", $order->self_work_price);
            } else {
                //本工作室账单情况
                $info = (new FinancialStatementsLog())
                    ->where([['order_id', '=', $order->order_id], ['work_id', '=', $order->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                    ->first();
                if (empty($info)) {
                    $data['money'] = $order->self_work_price;
                    $data['remarks'] = "分享课程收费";
                    return (new FinancialStatementsLog())->insert($data);
                }
                //分享工作室账单情况
                $info = (new FinancialStatementsLog())
                    ->where([['order_id', '=', $order->order_id], ['work_id', '=', $course->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                    ->first();
                if (empty($info)) {
                    $data['money'] = $order->share_work_price;
                    $data['work_id'] = $course->work_id;
                    return (new FinancialStatementsLog())->insert($data);
                }
                //工作室加钱
                (new DoctorWorks())->where([["id", '=', $order->work_id]])->increment("surplus", $order->self_work_price);
                (new DoctorWorks())->where([["id", '=', $course->doc_studio_id]])->increment("surplus", $order->share_work_price);
            }
        } elseif ($order->order_type == 2) {   //商品
            $data['type'] = 2;
            $data['settle_status'] = 0;
            $data['add_or_sub'] = 1;
            $goods = (new ProductGoods())->where([['id', '=', $order_goods->goods_id]])->first();
            $data['divide_type'] = 1;
            if ($goods->product_source == 1) { //工作室产品
                if ($goods->supplier_work_id == $order->work_id) { //工作室自己的产品
                    $info = (new FinancialStatementsLog())
                        ->where([['order_id', '=', $order->order_id], ['work_id', '=', $order->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                        ->first();
                    if (empty($info)) {
                        $data['money'] = $order->self_work_price;
                        $data['remarks'] = "商品收费";
                        (new FinancialStatementsLog())->insert($data);
                        //发送短信给工作室
                        $ali_sms = new AliSms();
                        $phone =  (new Doctor())->where([["work_id", '=', $order->work_id],['is_admin','=',1]])->value("account");
                        $ali_sms::sendMessage($phone,"",4);
                    }
                } else { //分享产品
                    //本工作室账单情况
                    $info = (new FinancialStatementsLog())
                        ->where([['order_id', '=', $order->order_id], ['work_id', '=', $order->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                        ->first();
                    if (empty($info)) {
                        $data['remarks'] = "分享商品收费";
                        $data['money'] = $order->self_work_price;
                        (new FinancialStatementsLog())->insert($data);
                    }
                    //分享工作室账单情况
                    $info = (new FinancialStatementsLog())
                        ->where([['order_id', '=', $order->order_id], ['work_id', '=', $goods->supplier_work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                        ->first();
                    if (empty($info)) {
                        $data['money'] = $order->share_work_price;
                        $data['work_id'] = $goods->supplier_work_id;
                        (new FinancialStatementsLog())->insert($data);
                    }
                }
            } elseif ($goods->product_source == 2) {  //供应商产品
                //本工作室账单情况
                $info = (new FinancialStatementsLog())
                    ->where([['order_id', '=', $order->order_id], ['work_id', '=', $order->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                    ->first();
                if (empty($info)) {
                    $data['money'] = $order->self_work_price;
                    $data['remarks'] = "供应商商品收费";
                    (new FinancialStatementsLog())->insert($data);
                }
                //供应商账单情况
                $info = (new FinancialStatementsLog())
                    ->where([['order_id', '=', $order->order_id], ['work_id', '=', $goods->supplier_work_id], ['divide_type', '=', 2], ['add_or_sub', '=', 1]])
                    ->first();
                if (empty($info)) {
                    $data['money'] = $order->supplier_price;
                    $data['work_id'] = $goods->supplier_work_id;
                    $data['divide_type'] = 2;
                    $data['remarks'] = "卖出商品收费";
                    (new FinancialStatementsLog())->insert($data);
                    //发送短信给工作室
                    $ali_sms = new AliSms();
                    $phone =  (new AdminUser())->where([["id", '=', $goods->supplier_work_id]])->value("username");
                    $ali_sms::sendMessage($phone,"",4);
                }
            }
        } elseif ($order->order_type == 3 || $order->order_type == 4) { //图文||电话
            $case = (new CaseDescribe())->where([['id', '=', $order_goods->specs_id]])->first();
            $data['sex'] = $case->sex;
            $data['age'] = $case->age;
            $data['type'] = 3;
            $data['settle_status'] = 0;
            $data['add_or_sub'] = 1;
            $data['divide_type'] = 1;
            $info = (new FinancialStatementsLog())
                ->where([['order_id', '=', $order->order_id], ['work_id', '=', $order->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                ->first();
            if (empty($info)) {
                $data['money'] = $order->self_work_price;
                $data['remarks'] = "咨询收费";
                (new FinancialStatementsLog())->insert($data);
                //给医生发短信
                $ali_sms = new AliSms();
                $phone =  (new Doctor())->where([["id", '=', $order_goods->goods_id]])->value("account");
                $ali_sms::sendMessage($phone,"",3);
            }
        }
        return true;
    }




    //公有方法调用支付
    public function doPay($data)
    {
        $res = self::pay($data);
        if (is_string($res)) {
            return $res;
        } else {
            return false;
        }
    }

    /**
     * @param $data
     * @return bool|void
     * @throws \Exception
     * 支付宝退款
     */
    public function doReturn($data)
    {
        $res = self::baseReturn($data);
        if ($res == "success") {
            return $res;
        } else {
            return false;
        }
    }
    
}
